package com.ng.biz.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.jfinal.plugin.activerecord.Db;
import com.ng.biz.model.domain.*;
import com.ng.biz.service.IDbapi;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class DbapiImpl implements IDbapi {

	@Override
	public void deleteGroupByIds(String id) {
		deleteChildrens(id);
		Db.delete("delete from " + DbapiReqArguments.TABLE_NAME + " where api_id in (select id from "+Dbapi.TABLE_NAME+" where group_id=?)", id);
		Db.delete("delete from " + DbapiSql.TABLE_NAME + " where api_id in (select id from "+Dbapi.TABLE_NAME+" where group_id=?)", id);
		Db.delete("delete from " + Dbapi.TABLE_NAME + " where group_id=?", id);
		DbapiGroup.dao.deleteById(id);
	}
	
	private void deleteChildrens(String id) {
		List<DbapiGroup> dbapiGroups = DbapiGroup.dao.find("select id from " + DbapiGroup.TABLE_NAME + " where parent_id=?", id);
		for (DbapiGroup dbapiGroup : dbapiGroups) {
			deleteChildrens(dbapiGroup.getId());
			Db.delete("delete from " + DbapiReqArguments.TABLE_NAME + " where api_id in (select id from "+Dbapi.TABLE_NAME+" where group_id=?)", dbapiGroup.getId());
			Db.delete("delete from " + DbapiSql.TABLE_NAME + " where api_id in (select id from "+Dbapi.TABLE_NAME+" where group_id=?)", dbapiGroup.getId());
			Db.delete("delete from " + Dbapi.TABLE_NAME + " where group_id=?", dbapiGroup.getId());
			dbapiGroup.delete();
		}
	}

}
